require 'openssl'
OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE
require 'net/http'
class WeixinAccesstoken < ApplicationRecord
  def self.get_token(source, app_id, app_secret)

    token = WeixinAccesstoken.find_by(source: source)
    if token
      if (Time.now - token.updated_at).to_i > 7100
        token.update_attribute(:access_token, get_access_token_from_weixin(app_id, app_secret) )
      end
    else
      token = WeixinAccesstoken.create!(source: source, access_token: get_access_token_from_weixin(app_id, app_secret))
    end
    token.access_token
  end

  def self.get_access_token_from_weixin(app_id, app_secret)
    uri = URI("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=#{app_id}&secret=#{app_secret}")
    respond = Net::HTTP.get_response(uri)
    if token = ActiveSupport::JSON.decode(respond.body)['access_token']
      token
    else
      raise
    end
  end
end
